package com.pwser.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import com.pwser.entities.Menu;
import com.pwser.entities.User;
import com.pwser.entities.UserDetailsImpl;
import com.pwser.mapper.LoginMapper;

@Service
public class LoginService implements UserDetailsService {

	@Autowired
	private LoginMapper loginMapper;

	@Override
	public UserDetails loadUserByUsername(String account) throws UsernameNotFoundException {
		User user = loginMapper.findUserByAccount(account);
		if (user == null) {
			throw new BadCredentialsException("登录失败：登陆账号不存在");
		}
		
		if(user.getLoginStatus().equals("1")) {
			throw new LockedException("登录失败：登陆账号被锁定，请联系管理员");
		}

		// 查到User后将其封装为UserDetails的实现类的实例供程序调用
		// 用该User和它对应的Role实体们构造UserDetails的实现类
		return new UserDetailsImpl(user.getLoginAccount(), 
				user.getLoginPass(), 
				user.getLoginStatus(), 
				loginMapper.findRolesByAccount(user.getLoginAccount()));
	}
	
	public List<Menu> getAllMenus() {
		return loginMapper.findAllMenus();
	}
	
	//将所有用户的密码改为BCryptPasswordEncoder编码
	public void updateAllUserEncodedPassword() {
		List<User> users = loginMapper.findAllUsers();
		for(User user : users) {
			BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
			String encodedPassword = passwordEncoder.encode(user.getLoginPass().trim());
			user.setLoginPass(encodedPassword);
			loginMapper.updateUserPassword(user);
		}
	}
	
}
